package com.yxinsur.imc.framework.aspectj;

import com.yxinsur.imc.common.annotation.DataScope;
import com.yxinsur.imc.common.annotation.Tenant;
import com.yxinsur.imc.common.core.domain.BaseEntity;
import com.yxinsur.imc.common.core.domain.BaseImcEntity;
import com.yxinsur.imc.common.core.domain.entity.SysRole;
import com.yxinsur.imc.common.core.domain.entity.SysUser;
import com.yxinsur.imc.common.core.domain.model.LoginUser;
import com.yxinsur.imc.common.utils.ServletUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.common.utils.spring.SpringUtils;
import com.yxinsur.imc.framework.web.service.TokenService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 租户过滤处理
 * @author imc
 */
@Aspect
@Component
public class TenantAspect
{
    /**
     * 数据权限过滤关键字
     */
    public static final String TENANT_AUTH = "tenantAuth";

    // 配置织入点
    @Pointcut("@annotation(com.yxinsur.imc.common.annotation.Tenant)")
    public void dataScopePointCut()
    {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable
    {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint)
    {
        // 获得注解
        Tenant tenant = getAnnotationTenant(joinPoint);
        if (tenant == null)
        {
            return;
        }
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                tenantFilter(joinPoint, currentUser,tenant.alias());
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user 用户
     */
    public static void tenantFilter(JoinPoint joinPoint, SysUser user,String alias)
    {
        StringBuilder sqlString = new StringBuilder();
        sqlString.append(StringUtils.format(" AND {}.tenant_id  = {}  ", alias,user.getTenantId()));
        if (StringUtils.isNotBlank(sqlString.toString()))
        {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseImcEntity)
            {
                BaseImcEntity baseEntity = (BaseImcEntity) params;
                baseEntity.getParams().put(TENANT_AUTH, sqlString);
            }
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
            {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(TENANT_AUTH, sqlString);
            }
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Tenant getAnnotationTenant(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null)
        {
            return method.getAnnotation(Tenant.class);
        }
        return null;
    }
}
